//
//  APVideoDetailViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/12.
//

#import "APVideoDetailViewController.h"
#import "APVideoDetailNaviBar.h"
#import "APBottomMenuViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "APVideoCommentInputView.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "APVideoCommentCell.h"
#import "NSString+Category.h"
#import "APCommentModel.h"
#import "APLoginManager.h"
#import "APVideoCommentView.h"
#import "APVideoDataManager.h"

@interface APVideoDetailViewController ()
@property (nonatomic, strong) APVideoDetailNaviBar *videoNaviBar;
@property (nonatomic, strong) UIImageView *videoImageView;
@property (nonatomic, strong) AVPlayer *videoPlayer;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) UIButton *commentButton;
@property (nonatomic, strong) APVideoCommentInputView *commentInputView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) APVideoCommentView *commentView;
@end

@implementation APVideoDetailViewController

- (APVideoCommentView *)commentView{
    if (!_commentView) {
        _commentView  = [[APVideoCommentView alloc] init];
    }
    return _commentView;
}

- (APVideoDetailNaviBar *)videoNaviBar{
    if (!_videoNaviBar) {
        _videoNaviBar = [[APVideoDetailNaviBar alloc] init];
        [_videoNaviBar.backButton addTarget:self action:@selector(videoBackButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
        [_videoNaviBar.moreButton addTarget:self action:@selector(moreButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [_videoNaviBar.upvoteButton addTarget:self action:@selector(upvoteButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _videoNaviBar;
}

- (APVideoCommentInputView *)commentInputView{
    if (!_commentInputView) {
        _commentInputView = [[APVideoCommentInputView alloc] init];
        [_commentInputView.sendButton addTarget:self action:@selector(sendButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commentInputView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self refreshData];
   
}

- (void)sendButtonDidClick:(UIButton *)sender{
    NSString *content = self.commentInputView.textView.textView.text;
    if ([content ap_isNullString]) {
        return;
    }
    APUserModel *userModel = [[APLoginManager shareInstance] userInfo];
    APCommentModel *model = [[APCommentModel alloc] init];
    model.userId = userModel.userId;
    model.avatar = userModel.avatarUrl;
    model.nickname = userModel.nickname;
    model.content = content;
    self.commentInputView.textView.textView.text = @"";
    APVideoCommentItemView *itemView = [[APVideoCommentItemView alloc] init];
    itemView.commentModel = model;
    [self.commentView.stackView addArrangedSubview:itemView];
    [self performSelector:@selector(removeComment:) withObject:itemView afterDelay:5];
}


- (void)removeComment:(APVideoCommentItemView *)itemView{
    if (_commentView.stackView) {
        [self.commentView.stackView removeArrangedSubview:itemView];
        [itemView removeFromSuperview];
    }
}

- (void)commentButtonDidClick:(UIButton *)sender{
    [self.commentInputView.textView.textView becomeFirstResponder];
}



- (void)refreshData{
    APBroadcasterModel *userModel = [[APUserDataManager shareInstance] searchUserByUserId:_videoModel.userId];
    _videoModel.isFollow = userModel.isFriend;
    [_videoNaviBar.avatarControl.avatarImageView sd_setImageWithURL:[NSURL URLWithString:_videoModel.avatar]];
    _videoNaviBar.nameLabel.text = _videoModel.nickname;
    _videoNaviBar.upvoteButton.selected = _videoModel.isUpvote;
    [_videoImageView sd_setImageWithURL:[NSURL URLWithString:_videoModel.middleThumbUrl]];
    BOOL isSelf = [_videoModel.userId isEqualToString:[[APLoginManager shareInstance] userInfo].userId];
    _videoNaviBar.upvoteButton.hidden = isSelf;
    _videoNaviBar.avatarControl.followButton.hidden = true;
    _videoNaviBar.moreButton.hidden = isSelf;
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([object isEqual:self.videoPlayer] && [keyPath isEqualToString:@"status"]) {
        if (self.videoPlayer.status == AVPlayerStatusReadyToPlay) {
            [self.videoPlayer play];
            int seconds = _videoModel.isCreate ? 1:2;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.videoImageView.hidden = true;
                [self.view removeProgress];
            });
        }
    }
}

- (void)videoPlayDidEnd:(NSNotification *)noti{
    [self.videoPlayer seekToTime:kCMTimeZero toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {}];
}


- (void)moreButtonDidClick:(UIButton *)sender{
    APBottomMenuViewController *menuVC = [[APBottomMenuViewController alloc] init];
    [menuVC setCallBack:^(NSInteger index) {
        if (index == 1) {
            [self.navigationController popViewControllerAnimated:true];
        }else{
            [self refreshData];
        }
    }];
    menuVC.userId = _videoModel.userId;
    [self.tabBarController presentViewController:menuVC animated:true completion:nil];
}

- (void)upvoteButtonDidClick:(UIButton *)sender{
    _videoModel.isUpvote = !_videoModel.isUpvote;
    [[APVideoDataManager shareInstance] updateVideo];
    [self refreshData];
}
- (void)videoBackButtonDidClick{
    [self.navigationController popViewControllerAnimated:false];
}

- (void)initUI{
    NSURL *url = _videoModel.isCreate ? [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/%@",VIDEO_RECORDFILE_FOLDER_PATH,_videoModel.mediaUrl]]:[NSURL URLWithString:_videoModel.mediaUrl];
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:url];
    
    _videoPlayer = [[AVPlayer alloc] initWithPlayerItem:playerItem];
    _videoPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
    float volume = [[AVAudioSession sharedInstance] outputVolume];
    _videoPlayer.volume = volume;
    if ([_videoPlayer respondsToSelector:@selector(automaticallyWaitsToMinimizeStalling)]) {
        _videoPlayer.automaticallyWaitsToMinimizeStalling = NO;
    }
    
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.videoPlayer];
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    [self.view.layer addSublayer:self.playerLayer];
    self.playerLayer.frame = self.view.bounds;

    [self.videoPlayer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoPlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    _videoImageView = [[UIImageView alloc]init];
    _videoImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:_videoImageView];
    [_videoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.videoNaviBar];
    [self.videoNaviBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
    }];

    
    _commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_commentButton setBackgroundImage:[UIImage imageNamed:@"video_comment_icon"] forState:UIControlStateNormal];
    [_commentButton addTarget:self action:@selector(commentButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_commentButton];
    [_commentButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-37);
        make.bottom.equalTo(self.view).offset(-22);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    [self.view addSubview:self.commentInputView];
    self.commentInputView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 52);
    
    
    [self.view addSubview:self.commentView];
    [self.commentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.bottom.equalTo(self.view).offset(-50);
        make.right.equalTo(self.view).offset(-70);
        make.top.equalTo(self.view).offset(100);
    }];
    [self addObservers];
    [self.view ShowProgress];
}

- (void)addObservers{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - 处理键盘遮挡
- (void)keyboardWillShow:(NSNotification *)noti{
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyY = frame.size.height;
    self.commentInputView.frame = CGRectMake(0, ScreenHeight - keyY- 52, ScreenWidth, 52);
    [self.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-(keyY + 20 + 52));
    }];
}

//键盘收回
- (void)keyboardWillHide:(NSNotification *)noti{
    self.commentInputView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 52);
    [self.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-50);
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = false;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = true;

}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    [_commentButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-(self.view.safeAreaInsets.bottom + 22));
    }];
}
- (void)dealloc{
    @try {
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [self.videoPlayer removeObserver:self forKeyPath:@"status"];
        if (_videoPlayer) {
            [self.videoPlayer pause];
            [self.playerLayer removeFromSuperlayer];
            _videoPlayer = nil;
        }
    } @catch (NSException *exception) {
    } @finally {
    }
}

@end
